package com.tjl.foodapp;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link CollectFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CollectFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public CollectFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
      * @param param2 Parameter 2.
     * @return A new instance of fragment CollectFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CollectFragment newInstance(String param1, String param2) {
        CollectFragment fragment = new CollectFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }
    //页面元素
    public static RadioGroup group;
    RecyclerView rv_collect_center;
    //上下文
    Context context;
    //请求队列
    RequestQueue queue;
    //收藏店铺数据源列表
    ArrayList<Collect> shopList = new ArrayList<Collect>();
    //收藏食物数据源列表
    ArrayList<Collect> foodList = new ArrayList<Collect>();
    //收藏店铺列表适配器
    class MyShopAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  LayoutInflater.from(context).inflate(R.layout.collect_shop_item,null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ViewHolder viewHolder = (ViewHolder)holder;
            Collect collect = shopList.get(position);
            getItemByURL(Utils.urlBase+"and_getShopByShopId.do?id="+collect.getShop_id(),
                    "shop",viewHolder);
            viewHolder.btn_enter_collectshop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("shop_id",collect.getShop_id());
                    bundle.putString("shopname",collect.getShopname());
                    bundle.putString("prePage","shopcollect");
                    changeFragment(new FoodListFragment(),bundle,"foodlist");
                }
            });
            viewHolder.btn_cancel_collectshop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteCollect(Utils.urlBase+"and_deleteCollect.do?id="+collect.getCollect_id());
                }
            });
        }

        @Override
        public int getItemCount() {
            return shopList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder{
           ImageView img_shop_collectitem;
           TextView tx_shopname_collectitem;
           TextView tx_address_collectitem;
           Button btn_enter_collectshop,btn_cancel_collectshop;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                img_shop_collectitem = itemView.findViewById(R.id.img_shop_collectitem);
                tx_shopname_collectitem = itemView.findViewById(R.id.tx_shopname_collectitem);
                tx_address_collectitem = itemView.findViewById(R.id.tx_address_collectitem);
                btn_enter_collectshop = itemView.findViewById(R.id.btn_endter_collectshop);
                btn_cancel_collectshop = itemView.findViewById(R.id.btn_cancel_collectshop);
            }
        }
    }
    class MyFoodAdaper extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view =  LayoutInflater.from(context).inflate(R.layout.collect_food_item,null);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            ViewHolder viewHolder = (ViewHolder)holder;
            Collect collect = foodList.get(position);
            getItemByURL(Utils.urlBase+"and_getFoodByFoodId.do?id="+collect.getFood_id(),
                    "food",viewHolder);
            viewHolder.btn_enter_collectfood.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    int id = Integer.parseInt(viewHolder.tx_shopid_collectitem.getText().toString());
                    bundle.putInt("shop_id",id);
                    bundle.putInt("food_id",collect.getFood_id());
                    bundle.putString("prePage","foodcollect");
                    changeFragment(new FoodDetailFragment(),bundle,"fooddetail");
                }
            });
            viewHolder.btn_cancel_collectfood.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    deleteCollect(Utils.urlBase+"and_deleteCollect.do?id="+collect.getCollect_id());
                }
            });

        }

        @Override
        public int getItemCount() {
            return foodList.size();
        }
        class ViewHolder extends RecyclerView.ViewHolder{
           ImageView img_food_collectitem;
           TextView tx_foodname_collectitem;
           TextView tx_price_collectitem;
           TextView tx_shopid_collectitem;
           Button btn_enter_collectfood,btn_cancel_collectfood;
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
               img_food_collectitem = itemView.findViewById(R.id.img_food_collectitem);
               tx_foodname_collectitem = itemView.findViewById(R.id.tx_foodname_collectitem);
               tx_price_collectitem = itemView.findViewById(R.id.tx_price_collectitem);
               btn_enter_collectfood = itemView.findViewById(R.id.btn_enter_collectfood);
               btn_cancel_collectfood = itemView.findViewById(R.id.btn_cancel_collectfood);
               tx_shopid_collectitem = itemView.findViewById(R.id.tx_shopid_collectitem);
            }
        }
    }
    MyShopAdaper shopAdaper;
    MyFoodAdaper foodAdaper;
    //子页面管理器，用于页面跳转
    FragmentManager manager;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_collect, container, false);
        group = view.findViewById(R.id.rg_collect_head);
        rv_collect_center = view.findViewById(R.id.rv_collect_center);
        context = this.getActivity();
        manager = this.getActivity().getSupportFragmentManager();
        queue = Volley.newRequestQueue(context);
        shopAdaper = new MyShopAdaper();
        foodAdaper = new MyFoodAdaper();
        rv_collect_center.setLayoutManager(new LinearLayoutManager(context));
        Bundle bundle= this.getArguments();
        String page = bundle.getString("page");
        if(page.equals("shop")){
            group.check(R.id.btn_shop_head);
            rv_collect_center.setAdapter(shopAdaper);
        }else if(page.equals("food")){
            group.check(R.id.btn_food_head);
            rv_collect_center.setAdapter(foodAdaper);
        }

        getArrayList(Utils.urlBase+"and_getShopCollect.do?id="+MainActivity.user_id,"shop");
        getArrayList(Utils.urlBase+"and_getFoodCollect.do?id="+MainActivity.user_id,"food");
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==R.id.btn_shop_head){
                    rv_collect_center.setAdapter(shopAdaper);
                }else if(checkedId ==R.id.btn_food_head){
                    rv_collect_center.setAdapter(foodAdaper);
                }
            }
        });
        return view;
    }
    public void getImageByURL(String url,ImageView imageButton){
        int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
        int cachSize = maxMemory/8;
        LruCache<String, Bitmap> lruCache = new LruCache<String,Bitmap>(cachSize);
        ImageLoader.ImageCache imageCache = new ImageLoader.ImageCache() {
            @Override
            public Bitmap getBitmap(String s) {
                return lruCache.get(s);
            }

            @Override
            public void putBitmap(String s, Bitmap bitmap) {
                lruCache.put(s,bitmap);
            }
        };
        ImageLoader loader = new ImageLoader(queue,imageCache);
        ImageLoader.ImageListener listener
                = ImageLoader.getImageListener(imageButton,
                R.drawable.ic_launcher_background,
                R.drawable.ic_launcher_foreground);
        loader.get(url,listener);
    }
    public void getItemByURL(String url,String type,Object obj){
        Response.Listener listener1 = new Response.Listener() {

            @Override
            public void onResponse(Object o) {
                if(type.equals("shop")){
                    MyShopAdaper.ViewHolder viewHolder = (MyShopAdaper.ViewHolder)obj;
                    Shop shop = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),Shop.class);
                    getImageByURL(Utils.urlBase+"image/"+shop.getPic()+".jpg",viewHolder.img_shop_collectitem);
                   viewHolder.tx_shopname_collectitem.setText(shop.getShopname());
                   viewHolder.tx_address_collectitem.setText(shop.getAddress());
                }else if(type.equals("food")){
                    MyFoodAdaper.ViewHolder viewHolder = (MyFoodAdaper.ViewHolder)obj;
                    Food food = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),Food.class);
                    getImageByURL(Utils.urlBase+"image/"+food.getPic()+".jpg",viewHolder.img_food_collectitem);
                    viewHolder.tx_foodname_collectitem.setText(food.getFoodname());
                    viewHolder.tx_price_collectitem.setText(food.getPrice()+"");
                    viewHolder.tx_shopid_collectitem.setText(food.getShop_id()+"");
                }
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接错误",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
    }
    public void getArrayList(String url,String type){
        Response.Listener listener1 = new Response.Listener(){

            @Override
            public void onResponse(Object o) {
                if(type.equals("shop")){
                shopList = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),new TypeToken<ArrayList<Collect>>(){}.getType());
                shopAdaper.notifyDataSetChanged();}
                else if(type.equals("food")){
                    foodList = new GsonBuilder().setDateFormat("MMM dd, yyyy, hh:mm:ss a").create().fromJson(o.toString(),new TypeToken<ArrayList<Collect>>(){}.getType());
                    foodAdaper.notifyDataSetChanged();
                }
            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener(){

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_LONG).show();
            }
        };
        JsonRequest request = new JsonArrayRequest(url,listener1,listener2);
        queue.add(request);
    }
    public void changeFragment(Fragment fragment,Bundle bundle,String tag){
        //清空子页面栈
        for(int i=0,count = manager.getBackStackEntryCount();i<count;i++){
            manager.popBackStack();
        }
        //创建一个子页面的事务，以便切换子页面
        FragmentTransaction transaction = manager.beginTransaction();
        //设置子页面的初始化参数
        fragment.setArguments(bundle);
        //切换子页面，让子页面显示到主页面的指定位置
        transaction.add(R.id.linear_fragment,fragment);
        //给栈中的子页面一个标签
        transaction.addToBackStack(tag);
        //提交事务
        transaction.commit();
    }
    public void deleteCollect(String url){
        Response.Listener listener1 = new Response.Listener() {
            @Override
            public void onResponse(Object o) {

            }
        };
        Response.ErrorListener listener2 = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        };
        JsonRequest request = new JsonObjectRequest(url,null,listener1,listener2);
        queue.add(request);
            getArrayList(Utils.urlBase+"and_getShopCollect.do?id="+MainActivity.user_id,"shop");
            getArrayList(Utils.urlBase+"and_getFoodCollect.do?id="+MainActivity.user_id,"food");
    }
}